package com.webank.service.impl;


import com.webank.bean.Block;
import com.webank.bean.Car;
import com.webank.bean.Record;
import com.webank.service.ChainService;
import com.webank.utils.Contants;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.List;

import static com.webank.utils.WriteAndReadBlock.readBlock;
import static com.webank.utils.WriteAndReadBlock.writeBlock;


/**
 * Created by kantlin on 2018/7/26.
 */
@Service
public class ChainServiceImpl implements ChainService {
    @Override
    public void uploadRecord(Record record) throws Exception {
        File file=new File(Contants.FILEPATH + "lastPreviousHash");
        if(file.exists()){
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(Contants.FILEPATH + "lastPreviousHash")));
            String hashCode = (String)in.readObject();
            Contants.previousHash = hashCode;
        }
        Block genesisBlock = new Block(Contants.previousHash, record);
        Contants.previousHash = genesisBlock.getBlockHash();
        writeBlock(genesisBlock);
    }



    @Override
    public List<Record> getRecords(Car car) throws Exception {
        String vin = car.getVIN();
        List<Record> records = readBlock(vin);
        return records;
    }
}
